﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;

namespace uTorrentNetClient.ModelDesign.FileHandling
{
    public class FileHandler
    {
        public static void SaveToXML<T>(T o, string filePath)
        {
            var fileInfo = new FileInfo(filePath);
            if (!fileInfo.Directory.Exists)
                fileInfo.Directory.Create();

            if(fileInfo.Exists)
                fileInfo.Delete();

            var fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
            var serializer = new XmlSerializer(typeof(T));
            serializer.Serialize(fs, o);
            fs.Close();
        }

        public static T LoadFromXML<T>(string filePath)
        {
            var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            var serializer = new XmlSerializer(typeof(T));
            var result = (T)serializer.Deserialize(fs);
            fs.Close();
            return result;
        }

        public static bool FileExists(string path)
        {
            return File.Exists(path);
        }
    }
}
